package com.lanou3g.hw0512.upload;

import com.sun.xml.internal.ws.api.fastinfoset.FastInfosetFeature;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by dllo on 18/5/14.
 */
@WebServlet(name = "uploadServlet", urlPatterns = "/upload")
public class uploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.修改编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.检测表单是否支持上传文件
        if (!ServletFileUpload.isMultipartContent(request)) {
            //如果不支持上传文件,就不用往下执行了
            return;
        }

        //2.创建ServletFileUpload对象,来上传文件
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload();
        //配置一些参数
        //3.1 负无穷支持上传的最大文件(30M)
        upload.setFileSizeMax(1024 * 1024 * 30);
        //3.2 支持的带表单中 其他数据,带文件,即使整个表达最大容量为40M
        upload.setFileSizeMax(1024 * 1024 * 40);
        //3.支持中文
        upload.setHeaderEncoding("utf-8");
        //4,需要制定 上传的文件要放在哪
        String path = getServletContext().getRealPath("./")
                + File.separator
                + "upload";
        File uploadDir = new File(path);
        if ((!uploadDir.exists())) {
            uploadDir.mkdirs();
            //5.真正的上传
            try {
                List<FileItem>fileItems= upload.parseRequest(request);
                if (fileItems!=null&&fileItems.size()>0){
                    //有上传的内容
                    for (FileItem fileItem : fileItems) {
                        //这个文件名绝对不能上传的文件名
                        String fileName= new File(fileItem.getName()).getName();
                        String filePath =path+File.separator+fileName;
                        File file = new File(filePath);
                        System.out.println(filePath);
                        //将来上传的文件写入我们自己的文件夹中
                        fileItem.write(file);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
